package com.thb.pay.feigin.filter;


import com.alibaba.fastjson.JSON;
import com.thb.pay.core.exception.RRException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>描述：错误转码业务异常</p>
 *
 * @date 2017/12/03
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {

        log.info("FeignErrorDecoder:{}, {}", methodKey, JSON.toJSONString(response));
        /**
         * 业务异常
         */
        int status = response.status();

        if (status < 400 || status >= 500) {
            return new ErrorDecoder.Default().decode(methodKey, response);
        }
        if (response.body() == null) {
            return new ErrorDecoder.Default().decode(methodKey, response);
        }

        try {
            String body = Util.toString(response.body().asReader());
            RRException exceptionResult = JSON.parseObject(body, RRException.class);
            if (exceptionResult != null) {
                return exceptionResult;
            }
            return new RRException(RRException.UNKNOWN_EXCEPTION, RRException.UNKNOWN_MESSAGE);
        } catch (Exception ignored) {
            log.error("FeignErrorDecoder.exception:" + ignored);
        }

        return new ErrorDecoder.Default().decode(methodKey, response);
    }

}
